// User state management store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, UserPreferences } from '@/types'
import { createUser } from '@/types'
import { STORAGE_KEYS } from '@/constants'

export const useUserStore = defineStore('user', () => {
  // State
  const currentUser = ref<User | null>(null)
  const preferences = ref<UserPreferences>({
    theme: 'light',
    language: 'zh-CN',
    notifications: true,
    soundEnabled: true
  })
  const isAuthenticated = ref(false)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const isAgent = computed(() => currentUser.value?.role === 'agent')
  const isClient = computed(() => currentUser.value?.role === 'client')
  const userName = computed(() => currentUser.value?.name || '')
  const userAvatar = computed(() => currentUser.value?.avatar || '/default-avatar.png')
  const userStatus = computed(() => currentUser.value?.status || 'offline')

  // Actions
  const setCurrentUser = (user: User | null) => {
    currentUser.value = user
    isAuthenticated.value = !!user
    if (user) {
      error.value = null
    }
  }

  const updateUser = (updates: Partial<User>) => {
    if (currentUser.value) {
      currentUser.value = {
        ...currentUser.value,
        ...updates,
        updatedAt: new Date()
      }
    }
  }

  const setUserStatus = (status: 'online' | 'offline' | 'away') => {
    if (currentUser.value) {
      currentUser.value.status = status
      currentUser.value.lastSeen = new Date()
      currentUser.value.updatedAt = new Date()
    }
  }

  const updatePreferences = (newPreferences: Partial<UserPreferences>) => {
    preferences.value = {
      ...preferences.value,
      ...newPreferences
    }
    savePreferencesToStorage()
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  const setError = (errorMessage: string | null) => {
    error.value = errorMessage
  }

  const clearError = () => {
    error.value = null
  }

  // Authentication actions
  const login = async (credentials: { email: string; password: string }) => {
    try {
      setLoading(true)
      clearError()
      
      // TODO: Replace with actual API call
      // const response = await authService.login(credentials)
      
      // Mock login for now
      const mockUser = createUser({
        name: '客服小明',
        email: credentials.email,
        role: 'agent',
        status: 'online'
      })
      
      setCurrentUser(mockUser)
      saveUserToStorage()
      
      return mockUser
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '登录失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const logout = async () => {
    try {
      setLoading(true)
      
      // TODO: Replace with actual API call
      // await authService.logout()
      
      setCurrentUser(null)
      clearUserFromStorage()
      clearError()
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '登出失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const refreshUser = async () => {
    if (!currentUser.value) return

    try {
      setLoading(true)
      
      // TODO: Replace with actual API call
      // const updatedUser = await userService.getCurrentUser()
      // setCurrentUser(updatedUser)
      
      // Mock refresh
      updateUser({ lastSeen: new Date() })
      saveUserToStorage()
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '刷新用户信息失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  // Storage helpers
  const saveUserToStorage = () => {
    if (currentUser.value) {
      localStorage.setItem('current_user', JSON.stringify(currentUser.value))
    }
  }

  const loadUserFromStorage = () => {
    try {
      const stored = localStorage.getItem('current_user')
      if (stored) {
        const user = JSON.parse(stored)
        // Convert date strings back to Date objects
        user.lastSeen = new Date(user.lastSeen)
        user.createdAt = new Date(user.createdAt)
        user.updatedAt = new Date(user.updatedAt)
        setCurrentUser(user)
      }
    } catch (err) {
      console.error('Failed to load user from storage:', err)
      clearUserFromStorage()
    }
  }

  const clearUserFromStorage = () => {
    localStorage.removeItem('current_user')
  }

  const savePreferencesToStorage = () => {
    localStorage.setItem(STORAGE_KEYS.USER_PREFERENCES, JSON.stringify(preferences.value))
  }

  const loadPreferencesFromStorage = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEYS.USER_PREFERENCES)
      if (stored) {
        preferences.value = { ...preferences.value, ...JSON.parse(stored) }
      }
    } catch (err) {
      console.error('Failed to load preferences from storage:', err)
    }
  }

  // Initialize store
  const initialize = () => {
    loadUserFromStorage()
    loadPreferencesFromStorage()
  }

  // Auto-save preferences when they change
  const startAutoSave = () => {
    // Save preferences every 5 seconds if they've changed
    setInterval(() => {
      savePreferencesToStorage()
      if (currentUser.value) {
        saveUserToStorage()
      }
    }, 5000)
  }

  return {
    // State
    currentUser,
    preferences,
    isAuthenticated,
    loading,
    error,
    
    // Getters
    isAgent,
    isClient,
    userName,
    userAvatar,
    userStatus,
    
    // Actions
    setCurrentUser,
    updateUser,
    setUserStatus,
    updatePreferences,
    setLoading,
    setError,
    clearError,
    login,
    logout,
    refreshUser,
    initialize,
    startAutoSave
  }
})